<template>
  <view class="step_status">
    <el-steps
        class="mb-4"
        style="display: flex;width: 100%;"
        :space="200"
        :active="active_step"
        simple
    >
      <el-step title="编辑资料" :icon="Edit" />
      <el-step title="图片上传" :icon="UploadFilled" />
      <el-step title="视频上传" :icon="Picture" />
    </el-steps>
  </view>

  <el-form :model="form" label-width="auto" style="max-width: 600px">
    <el-form-item label="电影名称" v-show="active_step==0">
      <el-input v-model="form.name" />
    </el-form-item>
    <el-form-item label="电影类型" v-show="active_step==0">
      <el-select
          v-model="form.type"
          multiple
          collapse-tags
          collapse-tags-tooltip
          :max-collapse-tags="5"
          placeholder="Select"
          style="width: 240px"
      >
        <el-option
            v-for="item in type_options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="电影日期" v-show="active_step==0">
      <el-col :span="11">
        <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="请选择一个日期"
            style="width: 100%"
        />
      </el-col>
    </el-form-item>
    <el-form-item label="电影评分" v-show="active_step==0">
      <el-rate v-model="form.score" allow-half :max="10"/>
    </el-form-item>
    <el-form-item label="电影时长" v-show="active_step==0">
      <el-input-number v-model="form.length" :min="1" :max="180" />
    </el-form-item>
    <el-form-item label="允许评论" v-show="active_step==0">
      <el-switch v-model="form.comment" />
    </el-form-item>
    <el-form-item label="允许点赞" v-show="active_step==0">
      <el-switch v-model="form.like" />
    </el-form-item>
    <el-form-item label="允许收藏" v-show="active_step==0">
      <el-switch v-model="form.stars" />
    </el-form-item>
    <el-form-item label="允许喜欢" v-show="active_step==0">
      <el-switch v-model="form.love" />
    </el-form-item>
    <el-form-item label="要求等级" v-show="active_step==0">
      <el-radio-group v-model="form.level">
        <el-radio value="0">非会员</el-radio>
        <el-radio value="1">普通会员</el-radio>
        <el-radio value="2">超级会员</el-radio>
        <el-radio value="3">super会员</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="简介" v-show="active_step==0">
      <el-input v-model="form.desc" type="textarea" />
    </el-form-item>
    <el-form-item label="状态" v-show="active_step==0">
      <el-select v-model="form.status" placeholder="请选择电影状态">
        <el-option label="启用" value="online" />
        <el-option label="禁用" value="offline" />
        <el-option label="隐藏" value="hide" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <view class="btn-items" v-show="active_step==1">
        <el-upload
            :action="fanart_uploadUrl"
            :http-request="fanart_uploadFile"
            accept="image/jpg"
            :show-file-list="false"
            :before-upload="beforeUpload"
        >
          <el-button size="small" type="primary">上传fanart</el-button>
        </el-upload>

<!--        <view v-if="active_upload_fanart">
          <el-image :src="movieData[0].fanart" style="width: 300px; height: 173px;border-radius: 20px;" fit="cover"/>
        </view>-->

        <el-upload
            :action="poster_uploadUrl"
            :http-request="poster_uploadFile"
            accept="image/jpg"
            :show-file-list="false"
            :before-upload="beforeUpload"
        >
          <el-button size="small" type="primary">上传poster</el-button>
        </el-upload>

<!--        <view v-if="active_upload_poster">
          <el-image :src="movieData[0].poster" style="width: 70%;border-radius: 1em;" fit="cover"/>
        </view>-->
      </view>
    </el-form-item>

    <el-form-item v-show="active_step==2">
      <view class="btn-items">
        <el-upload
            :action="video_uploadUrl"
            :http-request="video_uploadFile"
            accept="image/jpg"
            :show-file-list="false"
            :before-upload="beforeUpload_video"
        >
          <el-button size="small" type="primary">上传视频</el-button>
        </el-upload>

<!--        <view v-show="active_upload_video">
          <el-dialog v-model="onshow" title="预览" width="800px">
            <play_views :MID="md5(form.name)" @close-dialog="closeEditDialog"></play_views>
          </el-dialog>
        </view>-->

      </view>
    </el-form-item>


    <el-form-item v-show="active_step==0">
      <el-button type="primary" @click="onSubmit">新建</el-button>
      <el-button>Cancel</el-button>
    </el-form-item>

    <el-form-item v-show="active_step==1">
      <el-button type="primary" @click="next_step" :disabled="!(active_upload_fanart===true && active_upload_poster===true)">下一步</el-button>
      <el-button>Cancel</el-button>
    </el-form-item>

    <el-form-item v-show="active_step==2">
      <el-button type="primary" @click="next_step" :disabled="!active_upload_video">提交</el-button>
      <el-button>Cancel</el-button>
    </el-form-item>
  </el-form>

  <el-result
      icon="success"
      title="成功"
      :sub-title="movie_name"
      v-show="active_step==3"
      @click="back_step"
  >
    <template #extra>
      <el-button type="primary">返回</el-button>
    </template>
  </el-result>
</template>

<script lang="ts" setup>
import {reactive, ref} from 'vue'
import {ElLoading, ElMessage} from 'element-plus'
import {md5} from "js-md5";
import { Edit, Picture, UploadFilled } from '@element-plus/icons-vue'
import router from "@/router";
import W_Main_cen_video_card from "@/card/W_Main_cen_video_card.vue";
import play_views from "@/items/video_items/play_views.vue";

// 表单的响应式数据
const form = reactive({
  name: '',
  status: '',
  date: '',
  level: '',
  desc: '',
  like: true,
  comment: true,
  love: true,
  stars: true,
  score: 10,
  type:[],
  MID:'',
  length:0,
})

interface Movie {
  MID: string;
  fanart: string;
  poster: string;
  type: string;
  length: string;
  name: string;
  score: string;
  play_count:string;
  update_time:string;
  comment_count:string;
}

const movieData = ref<Movie[]>([]);

// 将长度字段转换为小时：分钟格式
const formatLength = (length: string): string => {
  const minutes = parseInt(length);
  if (minutes >= 60) {
    const hours = Math.floor(minutes / 60);
    const remainingMinutes = minutes % 60;
    return `${hours.toString().padStart(2, '0')}:${remainingMinutes.toString().padStart(2, '0')}:00`;
  } else {
    return `${minutes}分钟`;
  }
};

const fetchMovieData = async (MID) => {
  try {
    const response = await fetch('https://movie.cpb2013.top/movie_info.php?MID='+MID);
    const responseData = await response.json();
    if (responseData.status === 'ok') {
      movieData.value = responseData.data.map((movie: any) => ({
        MID: movie.MID,
        fanart: movie.fanart,
        poster: movie.poster,
        type: movie.type,
        length: formatLength(movie.length),
        name: movie.name,
        score: movie.score,
        play_count: movie.play_count,
        update_time: formatDate_Movie(movie.update_time),
        comment_count:movie.comment_count,
      }));
    } else {
      console.error('Error fetching movie data:', responseData.message);
    }
  } catch (error) {
    console.error('Error fetching movie data:', error);
  }
}

// 类型选择的选项
const type_options = [
  { value: '冒险', label: '冒险' },
  { value: '动画', label: '动画' },
  { value: '喜剧', label: '喜剧' },
  { value: '家庭', label: '家庭' },
  { value: '剧情', label: '剧情' },
  { value: '奇幻', label: '奇幻' },
  { value: '科幻', label: '科幻' },
  { value: '爱情', label: '爱情' },
  { value: '悬疑', label: '悬疑' },
]

// 上传相关的数据和方法
const fanart_uploadUrl = 'https://movie.cpb2013.top/admin/movie.php?mode=upload_fanart' // 替换为你的上传地址
const poster_uploadUrl = 'https://movie.cpb2013.top/admin/movie.php?mode=upload_poster' // 替换为你的上传地址
const video_uploadUrl = 'https://movie.cpb2013.top/admin/movie.php?mode=upload_video' // 替换为你的上传地址
const video_addUrl = 'https://movie.cpb2013.top/admin/movie.php?mode=add_video' // 替换为你的上传地址

const active_step = ref(0);

const active_upload_fanart = ref(false);
const active_upload_poster = ref(false);
const active_upload_video = ref(false);

const movie_name = ref('');

const next_step = () => {
  if (active_step.value++ > 3)
  {
    active_step.value = 0
  }
}

const back_step = () => {
  clearForm();
  active_step.value = 0;
}


const fanart_uploadFile = async ({ file }) => {
  let loading = openFullScreen();
  const formData = new FormData()
  formData.append('data', file)
  formData.append('MID', md5(form.name))
  formData.append('name', form.name)
  formData.append('key', localStorage.getItem('key'));
  try {
    const response = await fetch(fanart_uploadUrl, {
      method: 'POST',
      headers: {
        // 'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
      },
      body: formData,
    })

    if (response.ok) {
      const result = await response.json()
      if (result['status'] === 'success')
      {
        active_upload_fanart.value=true;
        ElMessage.success('上传成功！')
/*        await fetchMovieData(md5(form.name));*/
      }
      else if (result['status'] === 'danger') {
        localStorage.removeItem('key');
        ElMessage.error(result['msg']);
        await router.push('/login');
      }
    } else {
      ElMessage.error('上传失败！')
    }
  } catch (error) {
    ElMessage.error('上传失败！')
  }
  closeFullScreen(loading)
}

const poster_uploadFile = async ({ file }) => {
  let loading = openFullScreen();
  const formData = new FormData()
  formData.append('data', file)
  formData.append('MID', md5(form.name))
  formData.append('name', form.name)
  formData.append('key', localStorage.getItem('key'));
  try {
    const response = await fetch(poster_uploadUrl, {
      method: 'POST',
      headers: {
        // 'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
      },
      body: formData,
    })

    if (response.ok) {
      const result = await response.json()
      if (result['status'] === 'success')
      {
        active_upload_poster.value=true;
        ElMessage.success('上传成功！')
      }
      else if (result['status'] === 'danger') {
        localStorage.removeItem('key');
        ElMessage.error(result['msg']);
        await router.push('/login');
      }
    } else {
      ElMessage.error('上传失败！')
    }
  } catch (error) {
    ElMessage.error('上传失败！')
  }
  closeFullScreen(loading)
}

const video_uploadFile = async ({ file }) => {
  let loading = ElLoading.service({
    lock: true,
    text: '上传进度: 0%',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  const formData = new FormData();
  formData.append('data', file);
  formData.append('MID', md5(form.name));
  formData.append('name', form.name);
  formData.append('key', localStorage.getItem('key'));

  try {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', video_uploadUrl, true);

    xhr.timeout = 60000;

    xhr.upload.onprogress = (event) => {
      if (event.lengthComputable) {
        const percentComplete = (event.loaded / event.total) * 100;
        loading.setText(`上传进度: ${Math.round(percentComplete)}%`);
      }
    };

    xhr.onload = async () => {
      loading.close();
      if (xhr.status >= 200 && xhr.status < 300) {
        const response = JSON.parse(xhr.responseText);
        if (response.status === 'success') {
          active_upload_video.value = true;
          ElMessage.success('上传成功！');
        } else if (response.status === 'danger') {
          localStorage.removeItem('key');
          ElMessage.error(response.msg);
          await router.push('/login');
        }
      } else {
        ElMessage.error('上传失败！');
      }
    };

    xhr.onerror = () => {
      loading.close();
      ElMessage.error('上传失败！');
    };

    xhr.setRequestHeader('Accept', 'application/json');

    xhr.send(formData);
  } catch (error) {
    loading.close();
    ElMessage.error('上传失败！');
  }
};

const openFullScreen = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  return loading;
};

const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isLt3M = file.size / 1024 / 1024 < 3;

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG 格式!');
  }
  if (!isLt3M) {
    ElMessage.error('上传图片大小不能超过 3MB!');
  }
  return isJPG && isLt3M;
};

const beforeUpload_video = (file) => {
  const isMP4 = file.type === 'video/mp4';
  const isLt50M = file.size / 1024 / 1024 < 50;

  if (!isMP4) {
    ElMessage.error('上传视频只能是 MP4 格式!');
  }
  if (!isLt50M) {
    ElMessage.error('上传视频大小不能超过 50MB!');
  }
  return isMP4 && isLt50M;
};

const closeFullScreen = (loading) => {
  loading.close();
};
// 表单提交处理函数
const onSubmit = async () => {
  console.log('提交表单:', form)
  let loading = openFullScreen();
  const formData = new FormData()
  formData.append('key', localStorage.getItem('key'));
  // const { name, status, date, level, desc, like, comment, love, stars, score, type, MID, length } = toRefs(form);

  // 遍历并添加到 FormData
  Object.keys(form).forEach((key) => {
    // 排除那些不是字符串或数字的键（例如布尔值或对象）
    // 因为 FormData 主要用于处理键值对形式的字符串数据
    if (typeof form[key] === 'string' || typeof form[key] === 'number') {
      formData.append(key, form[key]);
    } else if (typeof form[key] === 'boolean') {
      // 对于布尔值，你可以决定如何转换为字符串（例如，使用 'true' 或 'false'）
      formData.append(key, form[key] ? 'true' : 'false');
    }
  });

  formData.append('type', form.type); // 直接添加 form.type 的值
  formData.append('date', formatDate(form.date)); // 直接添加 form.type 的值
  formData.set("MID",md5(form.name));

  movie_name.value=<string>formData.get('name')+',创建成功';

  try {
    const response = await fetch(video_addUrl, {
      method: 'POST',
      headers: {
        // 'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
      },
      body: formData,
    })

    if (response.ok) {
      const result = await response.json()
      if(result['status'] ==='success')
      {
        ElMessage.success('添加成功！')
        next_step();
      }
      else if (result['status'] === 'danger') {
        localStorage.removeItem('key');
        ElMessage.error(result['msg']);
        await router.push('/login');
      }
      else
      {
        ElMessage.error(result['msg'])
      }
    } else {
      ElMessage.error('添加失败！')
    }
  } catch (error) {
    ElMessage.error('请求失败！')
  }
  closeFullScreen(loading)
}
const formatDate = (date) => {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 将日期时间字符串转换为日期字符串
const formatDate_Movie = (datetime: string): string => {
  return datetime.split(' ')[0];
};

function clearForm() {
  for (const key in form) {
    if (form.hasOwnProperty(key)) {
      // Set each property to its initial value
      switch (typeof form[key]) {
        case 'string':
          form[key] = '';
          break;
        case 'number':
          form[key] = 0;
          break;
        case 'boolean':
          form[key] = false;
          break;
        default:
          form[key] = '';
      }
    }
  }
}
</script>
<style scoped>
.step_status
{
  width: 100%;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
}

</style>